package ldh.im.fxbase.dao;

import ldh.im.fxbase.data.pojo.ImFeedback;
import ldh.im.fxbase.data.pojo.ext.ImFeedbackExt;
import ldh.im.fxbase.data.pojo.status.ImFeedbackStatus;
import ldh.im.fxbase.util.DbUtil;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

public class ImFeedbackDao extends BaseDao {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImFeedbackDao.class);

    private static final String COLLECT_COLUMNS = "id, currentUserId, serverId, title, content, result, status statusValue, createTime, updateTime";

    public void insert(ImFeedback imFeedback) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            ResultSetHandler<Long> resultSetHandler = new ScalarHandler();
            String sql = String.format("insert into im_feedback(currentUserId, serverId, title, content, result, status, createTime, updateTime) values(?, ?, ?, ?, ?, ?, ?, ?)");
            Long id = queryRunner.insert(connection, sql, resultSetHandler, imFeedback.getCurrentUserId(), imFeedback.getServerId(), imFeedback.getTitle(), imFeedback.getContent(),
                    imFeedback.getResult(), valueEnum(imFeedback.getStatus()), imFeedback.getCreateTime(), imFeedback.getUpdateTime());
            imFeedback.setId(id);
            return imFeedback;
        });
    }

    public void delete(ImFeedback imFeedback) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            ResultSetHandler<Long> resultSetHandler = new ScalarHandler();
            String sql = String.format("update im_feedback set status =?, updateTime = ? where id = ? ");
            int n = queryRunner.update(connection, sql, resultSetHandler, valueEnum(ImFeedbackStatus.delete),
                    imFeedback.getUpdateTime(), imFeedback.getId());
            if (n != 1) {
                throw new RuntimeException("更新数据失败");
            }
            return imFeedback;
        });
    }

    public void batchInsert(List<ImFeedback> feedbacks) throws SQLException {
        if (feedbacks.size() < 1) return;
        DbUtil.transaction((queryRunner, connection) -> {
            ArrayListHandler h = new ArrayListHandler();
            Object[][] paras = feedbacks.stream().map(feedback-> new Object[] {feedback.getCurrentUserId(), feedback.getServerId(), feedback.getTitle(), feedback.getContent(), feedback.getResult(),
                    valueEnum(feedback.getStatus()), feedback.getCreateTime(), feedback.getUpdateTime()}).toArray(Object[][]::new);
            String sql = String.format("insert into im_feedback(currentUserId, serverId, title, content, result, status, createTime, updateTime) values(?, ?, ?, ?, ?, ?, ?, ?)");
            List<Object[]> ids = queryRunner.insertBatch(connection, sql, h, paras);
            for (int i=0; i<feedbacks.size(); i++) {
                feedbacks.get(i).setId((Long)ids.get(i)[0]);
            }

            return ids;
        });
    }

    public void batchUpdate(List<ImFeedback> feedbacks) throws SQLException {
        if (feedbacks.size() < 1) return;
        DbUtil.transaction((queryRunner, connection) -> {
            ArrayListHandler h = new ArrayListHandler();
            Object[][] paras = feedbacks.stream().map(feedback-> new Object[] {feedback.getResult(), valueEnum(feedback.getStatus()), feedback.getUpdateTime(), feedback.getCurrentUserId(),
                    feedback.getTitle()}).toArray(Object[][]::new);
            String sql = String.format("update im_feedback set result = ?, status = ?, updateTime = ? where currentUserId = ? and title = ?");
            int[] ns = queryRunner.batch(connection, sql, paras);
            if (ns.length != feedbacks.size()) {
                throw new RuntimeException("更新im_feedback失败， n =" + ns.length);
            }

            return ns.length;
        });
    }

    public List<ImFeedback> getAll(String userId, int size) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select %s from im_feedback where currentUserId = ? order by createTime desc limit 0, %s", COLLECT_COLUMNS, size);
            LOGGER.debug("getAll sql: {}", sql);
            List<ImFeedbackExt> feedbackExts = queryRunner.query(connection, sql, new BeanListHandler<>(ImFeedbackExt.class), userId);

            return feedbackExts.stream().map(c->c).collect(Collectors.toList());
        });
    }

    public ImFeedback getByTitle(String userId, String title) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select %s from im_feedback where currentUserId = ? and title = ?", COLLECT_COLUMNS);
            LOGGER.debug("getAll sql: {}", sql);
            ImFeedbackExt feedbackExt = queryRunner.query(connection, sql, new BeanHandler<ImFeedbackExt>(ImFeedbackExt.class), userId, title);

            return feedbackExt;
        });
    }
}
